import type { CardItem } from '../types/cardData';
import { getConfig, saveConfig } from './configService';
import * as path from 'path';

// Default trash directory name
const DEFAULT_TRASH_DIR = 'trash';

/**
 * Get the trash directory path from config or use default
 */
export async function getTrashPath(): Promise<string> {
  const config = await getConfig();
  
  // Use default if not configured
  if (!config.trash || !config.trash.path) {
    // If we have a local save path, create a trash subdirectory there
    if (config.dataSource && config.dataSource.localSavePath) {
      return path.join(config.dataSource.localSavePath, DEFAULT_TRASH_DIR);
    }
    
    // Otherwise return just the default name (main process will resolve it)
    return DEFAULT_TRASH_DIR;
  }
  
  return config.trash.path;
}

/**
 * Set the trash directory path in config
 */
export async function setTrashPath(trashPath: string): Promise<boolean> {
  try {
    const config = await getConfig();
    
    if (!config.trash) {
      config.trash = {};
    }
    
    config.trash.path = trashPath;
    await saveConfig(config);
    return true;
  } catch (error) {
    console.error('Failed to save trash path config:', error);
    return false;
  }
}

/**
 * Move a card to trash
 */
export async function moveCardToTrash(cardId: string): Promise<boolean> {
  try {
    return await window.electronAPI.moveCardToTrash(cardId);
  } catch (error) {
    console.error('Failed to move card to trash:', error);
    return false;
  }
}

/**
 * Permanently delete a card from trash
 */
export async function permanentlyDeleteCard(cardId: string): Promise<boolean> {
  try {
    return await window.electronAPI.permanentlyDeleteCard(cardId);
  } catch (error) {
    console.error('Failed to permanently delete card:', error);
    return false;
  }
}

/**
 * Restore a card from trash to normal storage
 */
export async function restoreCardFromTrash(cardId: string): Promise<boolean> {
  try {
    return await window.electronAPI.restoreCardFromTrash(cardId);
  } catch (error) {
    console.error('Failed to restore card from trash:', error);
    return false;
  }
}

/**
 * Get all cards from trash
 */
export async function getTrashCards(page: number = 1, pageSize: number = 20): Promise<{
  items: CardItem[];
  hasMore: boolean;
  total: number;
}> {
  try {
    const result = await window.electronAPI.getTrashCards(page, pageSize);
    return {
      items: result.cards || [],
      hasMore: result.hasMore || false,
      total: result.total || 0
    };
  } catch (error) {
    console.error('Failed to get trash cards:', error);
    return {
      items: [],
      hasMore: false,
      total: 0
    };
  }
}

/**
 * Empty trash (delete all cards permanently)
 */
export async function emptyTrash(): Promise<boolean> {
  try {
    return await window.electronAPI.emptyTrash();
  } catch (error) {
    console.error('Failed to empty trash:', error);
    return false;
  }
}